<template>
  <el-col :span="1.5">
    <el-button plain icon="Download" @click="handleExport">下载物流模板</el-button>
  </el-col>
  <el-col :span="1.5">
    <el-button type="primary" plain icon="UploadFilled" @click="handleImport">导入物流信息</el-button>
  </el-col>
  <el-dialog v-model="dialog.show" :title="dialog.title" width="500px">
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-form-item label="支付平台" prop="payType">
        <el-radio-group v-model="form.payType">
          <el-radio v-for="item in customPayList" :value="item.typeId">{{ item.name }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="dialog.type == 2" label="物流信息" prop="info">
        <el-upload
          ref="upload"
          class="upload-demo w-[100%]"
          drag
          accept=".xls,.xlsx"
          action="javascript:void(0)"
          :on-change="(file) => uploadExcel(1, file)"
          :auto-upload="false"
          :show-file-list="false"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">Drop file here or <em>click to upload</em></div>
          <template #tip>
            <div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template v-if="dialog.type == 1" #footer>
      <el-button type="primary" @click="submit">确定</el-button>
      <el-button @click="dialog.show = false">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import xlsx from 'xlsx';
import { trackPush } from '@/api/pay/PayOrder';
const props = defineProps({
  payList: {
    type: Array,
    default: () => []
  }
});
const customPayList = computed(() => {
  let arr = JSON.parse(JSON.stringify(props.payList));
  arr = arr
    .map((item) => {
      if (item.config) {
        if (typeof item.config === 'string') {
          item.config = JSON.parse(item.config?.replace(/\/\/\*\*\*.*\*\*\*.*\n/g, ''));
        }
      }
      return item;
    })
    .filter((item) => {
      return !(item.config?.logisticsConfig?.show == false || item.config?.logisticsConfig?.show == 'false');
    });
  return arr;
});
const rules = ref({
  payType: [{ required: true, message: '请选择支付平台', trigger: 'blur' }],
  info: [{ required: true, message: '请上传物流信息', trigger: 'blur' }]
});
const dialog = reactive({
  show: false,
  title: '',
  type: 1
});
const handleExport = () => {
  dialog.show = true;
  dialog.title = '下载物流模板';
  dialog.type = 1;
  cancel();
};
const handleImport = () => {
  dialog.show = true;
  dialog.title = '导入物流信息';
  dialog.type = 2;
  cancel();
};

let payTypeConfig = {};

const form = reactive({
  payType: ''
});
const formRef = ref(null);
const cancel = () => {
  formRef.value?.resetFields();
};
const submit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      let payType = customPayList.value.find((item) => item.typeId == form.payType);
      if (dialog.type == 1) {
        let config = payType.config;
        ElMessage.success('下载中,请稍后....');
        window.open(config.excelTemplateUrl, '_blank');
        dialog.show = false;
      }
      if (dialog.type == 2) {
      }
    }
  });
};

const upload = ref(null);
const emits = defineEmits(['success']);

function uploadExcel(type, file) {
  if (!form.payType) {
    ElMessage.error('请先选择支付平台');
    return false;
  }
  // 获取平台配置信息(校验表格)
  payTypeConfig = customPayList.value.find((item) => item.typeId == form.payType)?.config;
  const files = { 0: file.raw }; // 取到File
  readExcel(type, files);
}
const globalLoading = ref();
function readExcel(type, files) {
  // 表格导入
  if (files.length <= 0) {
    // 如果没有文件名
    return false;
  } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
    ElMessage.error('上传格式不正确，请上传xls或者xlsx格式');
    return false;
  }
  globalLoading.value = ElLoading.service({
    text: '正在校验表格数据，请稍候',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  const fileReader = new FileReader();
  fileReader.onload = (files) => {
    try {
      const data = files.target.result;
      const workbook = xlsx.read(data, {
        type: 'binary'
      });
      const wsname = workbook.SheetNames[0]; // 取第一张表
      const ws = xlsx.utils.sheet_to_json(workbook.Sheets[wsname]); // 生成json表格内容
      if (ws == null || ws.length === 0) {
        ElMessage.error('未读取到表格数据，请重新上传表格');
        upload.value.clearFiles();
      } else {
        entryList.value = [];
        ws.forEach((obj, index) => {
          let logisticsConfig = payTypeConfig.logisticsConfig;
          let arr = [...logisticsConfig?.logistItem, ...logisticsConfig?.addressItem];
          let item = {};
          arr.map((form) => {
            if (form.require) {
              if (!obj[form.label]) {
                ElMessage.error('[' + (index + 2) + ']行，未读取到【' + form.label + '】列');
                upload.value.clearFiles();
                throw new Error('[' + (index + 2) + ']行，未读取到【' + form.label + '】列');
                return;
              }
            }
            item[form.value] = obj[form.label];
          });
          entryList.value.push(item);
        });

        if (entryList.value.length > 0) {
          uploadTrack();
        } else {
          ElMessage.error('未读取到文件中数据');
        }
      }
    } catch (e) {
      if (globalLoading.value != null) {
        globalLoading.value.close();
      }
      return false;
    } finally {
      upload.value.clearFiles();
      globalLoading.value.close();
    }
  };
  fileReader.readAsBinaryString(files[0]);
}
const entryList = ref([]);
function uploadTrack() {
  if (entryList.value == null || entryList.value.length === 0) {
    ElMessage.error('未读取到文件中数据');
  }

  ElMessageBox.confirm('读取到' + entryList.value.length + '条物流信息，上传后自动同步到C端 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  })
    .then(() => {
      trackPush(entryList.value).then((response) => {
        ElMessage.success('上传成功！');
        emits('success');
        dialog.show = false;
      });
    })
    .catch(() => {
      ElMessage.info('已取消');
    });
}
</script>

<style lang="scss" scoped></style>
